/** 
 *
 */

var InsureOrderApplyManaged = function() {
	return {
		datatable : null,
        files : null,
		eles : [],//电梯ids
        totalamont:0,
        basedata:[],
		init : function() {
            $("#startTime").datetimepicker({lang:'ch',timepicker:false, format:"Y-m-d"});
            $("#endTime").datetimepicker({lang:'ch',timepicker:false, format:"Y-m-d"});
			this.initSearch();
			this.initListener();
            InsureOrderApplyManaged.showunitelebykey();
		},
		initSearch : function() {
			if (!jQuery().dataTable) {
				return;
			}
			var listTable = $("#InsureOrderListTable").dataTable({
				"sAjaxSource" : ctx + "/insureOrder/search?now=" + new Date().getTime(),
				/* 使用post方式 */
                "fnServerData" : function(sSource, aoData, fnCallback) {
                    var postData = {
                        page : 1,
                        start : 0,
                        rows : 10,
                        params : {}
                    };

                    if($('#orderNo').val()){
                        postData.params.orderNo = "%"+($('#orderNo').val()).replace(/\s/g,"%")+"%";
                    }

                    if($('#insureCompany').val()){
                        postData.params.insureCompany = "%"+($('#insureCompany').val()).replace(/\s/g,"%")+"%";
                    }

                    if($('#elevatorNumStart').val()){
                        postData.params.elevatorNumStart = "%"+($('#elevatorNumStart').val()).replace(/\s/g,"%")+"%";
                    }

                    if($('#elevatorNumEnd').val()){
                        postData.params.elevatorNumEnd = "%"+($('#elevatorNumEnd').val()).replace(/\s/g,"%")+"%";
                    }

                    if($('#orderAmountStart').val()){
                        postData.params.orderAmountStart = "%"+($('#orderAmountStart').val()).replace(/\s/g,"%")+"%";
                    }

                    if($('#orderAmountEnd').val()){
                        postData.params.orderAmountEnd = "%"+($('#orderAmountEnd').val()).replace(/\s/g,"%")+"%";
                    }

                    if($('#applyTimestime').val()){
                        postData.params.applyTimestime = "%"+($('#applyTimestime').val()).replace(/\s/g,"%")+"%";
                    }

                    if($('#applyTimeetime').val()){
                        postData.params.applyTimeetime = "%"+($('#applyTimeetime').val()).replace(/\s/g,"%")+"%";
                    }

                    // 参数
                    for (var i = 0, size = aoData.length; i < size; i++) {
                        if (aoData[i].name == 'iDisplayLength') {
                            postData.rows = aoData[i].value;
                        } else if (aoData[i].name == 'iDisplayStart') {
                            postData.start = aoData[i].value;
                        } else if (aoData[i].name == 'sEcho') {
                            postData.page = aoData[i].value;
                        }
                    }

                    // $.ajax({
                    //     "dataType" : 'json',
                    //     "type" : "POST",
                    //     "cache": false,
                    //     "url" : sSource,
                    //     "data" : postData,
                    //     "success" : function(data, textStatus, jqXHR){
                    //         fnCallback(data.data, textStatus, jqXHR);
                    //     }
                    // });
                },
				"bAutoWidth":false,
                "bPaginate": false, //翻页功能
                // "paging": false,
                // "bPaginate" : false,
                "iDisplayLength":10000,   //一页显示条数
				"aoColumnDefs" : [
						{
							"data" : "id",
							"aTargets" : [ 0 ],
                            "render": function (data, type, full, meta) {
                                return '<input type="checkbox"  class="checkchild"  value="' + data + '" />';
                            },
						},
						{
							"data" : "acceptUnit",
							"aTargets" : [ 1]
						},
						{
							"data" : "insureCompany",
							"aTargets" : [ 2 ]
						},
						{
							"data" : "insureLinkman",
							"aTargets" : [ 3 ]
						},
						{
							"data" : "insurePhone",
							"aTargets" : [ 4 ]
						},
						{
							"data" : "usingUnit",
							"aTargets" : [ 5 ]
						},
						{
							"data" : "usingArea",
							"aTargets" : [ 6 ]
						},
						{
							"data" : "usingAddress",
							"aTargets" : [ 7 ]
						},
						{
							"aTargets" : [ 8 ],
							"mRender" : function(data, type, full) {
								var btns =  '';
								// btns +=  Permission.createPermElement('insureOrder:list:del',' <button title="'+messages.public_button_del+'" href="javascript:;" class="btn btn-sm  btn-danger" name="del" target_id="'+full.id+'"><i class="fa fa-times"></i></button>');
								return btns;
							}
						}
				]
			});
			this.datatable = listTable;
		},reSearch:function(){
        	this.datatable.fnDraw();
        },removeClass:function(){//去除Form表单的验证样式
        	$('.form-group','#actForm').removeClass('has-success')
            .removeClass('has-error');
    		 $('span').remove('.help-block');
        },initListener : function() {
			/*
			 * 查询
			 */
			$("#searchBtn").click(function() {
				InsureOrderApplyManaged.reSearch();
				return false;
			});

			/*
			 * 清除
			 */
			$("#clearBtn").click(function() {
				$("#searchForm")[0].reset();
				return false;
			});

            $("#add").click(function() {
                InsureOrderApplyManaged.saveform();
                return false;
            });

            $("#cancel").click(function() {
                InsureOrderApplyManaged.clearform();
                return false;
            });

			/*
			 * 点击导入
			 */
            $("#import").click(function(e) {
                $("#filename").html("");
                $("#showImpDlg").modal("show");
                e.preventDefault();
            });

            /**
			 * 选择文件
             */
            $("#impelevator").click(function(){
                $(this).prev("input[type=file]").click();
            });

            $("input[type=file][name=excelFile]").change(function(){
                var that=this;
                var files=this.files;
                InsureOrderApplyManaged.files = files;
                var fileFatuiles="";
                $.each(files, function(index, file) {
                    $("#filename").html(file.name);
                    //存放大于5M上传失败的
                    if(file.size > 5*1024*1024){
                        if(fileFatuiles==""){
                            fileFatuiles=fileFatuiles+file.name;
                        } else {
                            fileFatuiles=fileFatuiles+","+file.name;
                        }
                        return ;
                    }
                });
                if(fileFatuiles.length > 0){
                	$(this).val("");
                    alert(fileFatuiles+"文件太大，超过5M，请调整后上传!");
                }
            });

            /**
             * 开始上传文件
             */
            $("#startimp").click(function(){
                var fileuploadUrl=ctx+"/insureOrderApply/impExcel?now=" + new Date().getTime();
                var files = InsureOrderApplyManaged.files;
                var fileFatuiles="";
                debugger;
                $.each(files, function(index, file) {
                    //存放大于5M上传失败的
                    if(file.size > 5*1024*1024){
                        if(fileFatuiles==""){
                            fileFatuiles=fileFatuiles+file.name;
                        } else {
                            fileFatuiles=fileFatuiles+","+file.name;
                        }
                        return ;
                    }
                    var data = new FormData();
                    data.append("excel", file);
                    $.ajax({
                        data:data,
                        type: "POST",
                        url:fileuploadUrl,
                        cache: false,
                        contentType: false,
                        processData: false,
                        success: function(data) {
                            $('#excelFile').val("");
                            if(data['type'] == "success" ) {
                            	$("#closeimp").click();
                                BootstrapDialog.show({
                                    title: '信息',
                                    message: '导入成功！',
                                    buttons: [
                                        {
                                            label: '确定',
                                            cssClass: 'btn blue',
                                            action: function(dialog) {
                                                dialog.close();
                                                InsureOrderApplyManaged.showelevatortable(data.data);
                                            }
                                        }]
                                });
                            }else{
                                BootstrapDialog.show({
                                    title: '信息',
                                    message: data.message,
                                    buttons: [
                                        {
                                            label: '确定',
                                            cssClass: 'btn blue',
                                            action: function(dialog) {
                                                dialog.close();
                                            }
                                        }]
                                });
                                return;
                            }
                        },
                        error: function(XMLHttpRequest, textStatus, errorThrown) {
                            debugger;
                        },
                    });
                });
                if(fileFatuiles.length > 0){
                    alert(fileFatuiles+"文件太大，超过5M，请调整后上传!");
                }
            });

			/*
			 * 预览投保单
			 */
			$("#show").click(function(e) {
			    $("#actDetailForm #insureCompany").val($("#actForm #insureCompany").val());
			    $("#actDetailForm #insureLinkman").val($("#actForm #insureLinkman").val());
			    $("#actDetailForm #insurePhone").val($("#actForm #insurePhone").val());
			    $("#actDetailForm #usingUnit").val($("#actForm #usingUnit").val());
			    $("#actDetailForm #usingArea").val($("#actForm #usingArea").val());
			    $("#actDetailForm #usingAddress").val($("#actForm #usingAddress").val());
			    $("#actDetailForm #acceptUnit").val($("#actForm #acceptUnitId option:selected").val());
                // $("#actDetailForm #InsureOrderListTable tbody").html($("#actForm #InsureOrderListTable tbody").html());
                $("#actDetailForm #elenum").html($("#actForm #elenum").html());
                $("#actDetailForm #eleamont").html($("#actForm #eleamont").html());
                $("#actDetailForm #eleamont").html($("#actForm #eleamont").html());
                $("#actDetailForm #ordertime").html($("#actForm #startTime").val() + " -- " + $("#actForm #endTime").val());
                InsureOrderApplyManaged.showedialoglevatortable();
				$("#showDetailDlg").modal("show");
                e.preventDefault();
			});
			
			// $('#InsureOrderListTable tbody')
			// 	.on('click', 'button[name="del"]',function() {
			// 		var id = $(this).attr("target_id");
			// 		InsureOrderApplyManaged.del(id);
			// 	});

			$('#thead_ck').change(function(){
				var ck = $(this).prop("checked");
				if(ck){
                    $('#InsureOrderListTable tbody input[type="checkbox"]').prop("checked", true);
				}else{
                    $('#InsureOrderListTable tbody input[type="checkbox"]').removeAttrs("checked");
				}
			});

			$('#deletebatch').click(function(e){
				var cklength = $('#InsureOrderListTable tbody input[type="checkbox"]:checked').length;
				if(cklength>0){
                    BootstrapDialog.show({
                        type : BootstrapDialog.TYPE_WARNING,
                        title : messages.public_cue_warning,
                        message : messages.public_cue_delSure,
                        buttons : [ {
                            label : messages.public_cue_close,
                            cssClass: 'btn btn-sm btn-default',
                            action : function(dialogItself) {
                                dialogItself.close();
                            }
                        }, {
                            label : messages.public_cue_sure,
                            cssClass : 'btn btn-sm btn-primary',
                            action : function(dialogItself) {
                                $('#InsureOrderListTable tbody input[type="checkbox"]:checked').each(function(){
                                    InsureOrderApplyManaged.sureDel($(this).val());
                                });
                                dialogItself.close();
                                BootstrapDialog.show({
                                    title : messages.public_cue_message,
                                    message : messages.public_cue_delSuccess,
                                    buttons : [ {
                                        label : messages.public_cue_sure,
                                        action : function(dialog) {
                                            dialog.close();
                                        }
                                    } ]
                                });
                            }
                        } ]
                    });
				}else{
                    BootstrapDialog.show({
                        title : messages.public_cue_message,
                        message : "请选择要删除的电梯",
                        buttons : [ {
                            label : messages.public_cue_sure,
                            action : function(dialog) {
                                dialog.close();
                            }
                        } ]
                    });
				}
			});
            // e.preventDefault();
            $("#actForm #usingUnit").blur(function(){
                InsureOrderApplyManaged.showunitele();
            });

            $("#actForm #usingArea").blur(function(){
                InsureOrderApplyManaged.showunitele();
            });

            $("#actForm #usingAddress").blur(function(){
                InsureOrderApplyManaged.showunitele();
            });

            //end
		},
		/**
		 * 删除
		 */
		del : function(id) {
			BootstrapDialog.show({
				type : BootstrapDialog.TYPE_WARNING,
				title : messages.public_cue_warning,
				message : messages.public_cue_delSure,
				buttons : [ {
					label : messages.public_cue_close,
					cssClass: 'btn btn-sm btn-default',
					action : function(dialogItself) {
						dialogItself.close();
					}
				}, {
					label : messages.public_cue_sure,
					cssClass : 'btn btn-sm btn-primary',
					action : function(dialogItself) {
                        InsureOrderApplyManaged.sureDel(id);
						dialogItself.close();
                        BootstrapDialog.show({
                            title : messages.public_cue_message,
                            message : messages.public_cue_delSuccess,
                            buttons : [ {
                                label : messages.public_cue_sure,
                                action : function(dialog) {
                                    dialog.close();
                                }
                            } ]
                        });
					}
				} ]
			});
			return false;
		},
		sureDel : function(id){
            InsureOrderApplyManaged.eles = $.grep(InsureOrderApplyManaged.eles, function(n, i){
                return id!=n.id;
			});
            var tarobj = $.grep(InsureOrderApplyManaged.basedata, function(n, i){
                return id==n.id;
            });
            var totalPremium = 0;
            // console.log(tarobj);
            if(tarobj){
                totalPremium = tarobj[0].totalPremium;
            }
            InsureOrderApplyManaged.basedata = $.grep(InsureOrderApplyManaged.basedata, function(n, i){
                return id!=n.id;
            });
            $('#tr'+id).remove();
            $("#elenum").html(InsureOrderApplyManaged.basedata.length+"台");
            InsureOrderApplyManaged.totalamont = InsureOrderApplyManaged.totalamont - parseFloat(totalPremium);
            $("#eleamont").html(InsureOrderApplyManaged.fixeddoubletwo(InsureOrderApplyManaged.totalamont)+"元");
		},
		showelevatortable : function(data){
		    var totalamont = 0;
            // InsureOrderApplyManaged.basedata = data;
            $.each(data, function(i, n){
                var obj = {};
                obj.id = n.id;
                obj.amount = n.totalPremium;
                obj.elevatorRate=n.elevatorRate;
                obj.starRate=n.starRate;
                InsureOrderApplyManaged.eles.push(obj);
                InsureOrderApplyManaged.basedata.push(n);
                totalamont = totalamont + n.totalPremium;

               var html = '<tr role="row" class="odd" id="tr'+n.id+'">' +
                       '<td><input type="checkbox" class="checkchild" value="'+n.id+'"></td>'+
                        InsureOrderApplyManaged.buildbasehtml(n)+
				   ' <td> <a title="删除" href="javascript:void(0);" class="btn btn-sm  btn-danger" name="" ' +
				   '    onclick="InsureOrderApplyManaged.del(\''+n.id+'\');"><i class="fa fa-times"></i></a>' +
				   '  </td>' +
				   ' </tr>'
				$("#InsureOrderListTable tbody").append(html);
			});
            $("#elenum").html(InsureOrderApplyManaged.basedata.length+"台");
            InsureOrderApplyManaged.totalamont = InsureOrderApplyManaged.totalamont + totalamont;
            $("#eleamont").html(InsureOrderApplyManaged.fixeddoubletwo(InsureOrderApplyManaged.totalamont)+"元");
		},
        showedialoglevatortable : function(){
            $("#actDetailForm #InsureOrderListTableDetail tbody").html("");
            var totalamont = 0;
            $.each(InsureOrderApplyManaged.basedata, function(i, n){
                totalamont = totalamont + n.totalPremium;
                var html = '<tr role="row" class="odd" id="tr'+n.id+'">' +
                    '<td>'+(i+1)+'</td>'+
                    InsureOrderApplyManaged.buildbasehtml(n)+
                    ' </tr>'
                $("#actDetailForm #InsureOrderListTableDetail tbody").append(html);
            });
        },
        buildbasehtml:function(n){
            // InsureOrderApplyManaged.buildnull(n.archiveNo)+'<br/>'+
            // +'<br/>'+InsureOrderApplyManaged.buildnull(n.deviceName)+'<br/>'+InsureOrderApplyManaged.buildnull(n.deviceType)
            //
            // InsureOrderApplyManaged.buildnull(n.useDep)+'<br/>'+InsureOrderApplyManaged.buildnull(n.placeType)
            // +'<br/>'+InsureOrderApplyManaged.buildnull(n.areaName)+'<br/>'+InsureOrderApplyManaged.buildnull(n.placeAddress)
            // +'<br/>'+InsureOrderApplyManaged.buildnull(n.deviceUseposition)
            //
            // InsureOrderApplyManaged.buildnull(n.deviceState)+'<br/>'+InsureOrderApplyManaged.buildnull(n.superviceState)
            //
            // n.floorNum+'<br/>'+n.doorNum+'<br/>'+n.stationsNum+'<br/>'+n.speed
            //
            // InsureOrderApplyManaged.buildnull(n.makeCompany)+'<br/>'+InsureOrderApplyManaged.buildnull(n.installCompany)
            // +'<br/>'+InsureOrderApplyManaged.buildnull(n.useDep)

            var basehtml =
                ' <td>'+InsureOrderApplyManaged.buildnull(n.registerCode)+'</td>' +
                ' <td>'+InsureOrderApplyManaged.buildnull(n.deviceName)+'</td>' +
                ' <td>'+InsureOrderApplyManaged.buildnull(n.placeType)+'</td>' +
                ' <td>'+InsureOrderApplyManaged.buildnull(n.useDep)+'</td>' +
                ' <td>'+InsureOrderApplyManaged.buildnull(n.deviceUseposition)+'</td>' +
                ' <td>'+InsureOrderApplyManaged.buildnull(n.deviceState)+'</td>' +
                ' <td>'+InsureOrderApplyManaged.fixeddoubletwo(n.totalPremium)+'</td>';
            return basehtml;
        },
        saveform : function(){
            if(InsureOrderApplyManaged.basedata.length == 0){
                BootstrapDialog.show({
                    title : messages.public_cue_cue,
                    message : "投保电梯信息不能为空",
                    buttons : [ {
                        label : messages.public_cue_sure,
                        cssClass : 'btn btn-sm btn-primary',
                        action : function(dialogItself) {
                            dialogItself.close();
                        }
                    } ]
                });
                return;
            }
            var form1 = $('#actForm');
            form1.validate({
                rules : {
                    insureCompany:{
                        maxlength : 25,
                        required : true
                    },
                    insureLinkman:{
                        maxlength : 25,
                        required : false
                    },
                    insurePhone:{
                        maxlength : 25,
                        required : false
                    },
                    usingUnit:{
                        maxlength : 25,
                        required : false
                    },
                    usingArea:{
                        maxlength : 25,
                        required : false
                    },
                    usingAddress:{
                        maxlength : 25,
                        required : false
                    },
                    acceptUnit:{
                        maxlength : 25,
                        required : false
                    }
                }
            });
            if(form1.valid()){
                var postData = $("form[name='actForm']").serializeJson();
                postData.eles = InsureOrderApplyManaged.eles;
                postData.elevatorNum = InsureOrderApplyManaged.eles.length;
                postData.orderAmount = InsureOrderApplyManaged.totalamont;
                if(postData["acceptUnitId"]){
                    postData.acceptUnit = $("#actForm #acceptUnitId option:selected").html();
                }
                // console.log(postData);
                $.ajax({
                    "dataType" : 'json',
                    "cache": false,
                    "type" : "POST",
                    "data" : JSON.stringify(postData),
                    "url" : ctx + "/insureOrder/edit?now="+new Date().getTime(),
                    "contentType" : 'application/json;charset=utf-8', //设置请求头信息
                    "success" : function(data) {
                        if(data.type=='success'){
                            $("#editDlg").modal("hide");
                            BootstrapDialog.show({
                                title : messages.public_cue_cue,
                                message : "投保单已投保，请等待审核",
                                buttons : [ {
                                    label : messages.public_cue_sure,
                                    cssClass : 'btn btn-sm btn-primary',
                                    action : function(dialogItself) {
                                        if(InsureOrderApplyManaged.type == 1){
                                            window.location.href = ctx+"/insureOrder/list.html";
                                        } if(InsureOrderApplyManaged.type == 2){
                                            window.location.href = ctx+"/insureOrder/ivalidList.html";
                                        }else{
                                            InsureOrderApplyManaged.clearform();
                                        }
                                        dialogItself.close();
                                    }
                                } ]
                            });

                        }else{
                            BootstrapDialog.show({
                                type : BootstrapDialog.TYPE_WARNING,
                                title : messages.public_cue_warning,
                                message : data.message,
                                buttons : [ {
                                    label : messages.public_cue_sure,
                                    cssClass : 'btn btn-sm btn-primary',
                                    action : function(dialogItself) {
                                        dialogItself.close();
                                    }
                                } ]
                            });
                        }
                    }
                });
            }else{
                BootstrapDialog.show({
                    type : BootstrapDialog.TYPE_WARNING,
                    title : messages.public_cue_warning,
                    message : "请先完善信息",
                    buttons : [ {
                        label : messages.public_cue_sure,
                        cssClass : 'btn btn-sm btn-primary',
                        action : function(dialogItself) {
                            dialogItself.close();
                        }
                    } ]
                });
            }
        },
        showunitele:function(){
            var usingUnit = $("#actForm #usingUnit").val();
            var usingArea = $("#actForm #usingArea").val();
            var usingAddress = $("#actForm #usingAddress").val();
            if(usingUnit == ""){
                return;
            }

            if(usingArea == ""){
                return;
            }

            if(usingAddress == ""){
                return;
            }
            var obj = {
                "useunitName":usingUnit,
                "placeArea":usingArea,
                "placeAddress":usingAddress
            };
            InsureOrderApplyManaged.execueyelist(obj);
        },
        showunitelebykey:function(){
            if(eyekey){
                var obj = {
                    "key":eyekey,
                };
                InsureOrderApplyManaged.execueyelist(obj);
            }
        },
        execueyelist:function(obj){
            var url = ctx+"/insureOrderApply/showeyebyUseuni?now=" + new Date().getTime();
            $.ajax({
                data: JSON.stringify(obj),
                type: "POST",
                url:url,
                cache: false,
                dataType : 'json',
                processData: false,
                contentType : 'application/json;charset=utf-8', //设置请求头信息
                success: function(data) {
                    InsureOrderApplyManaged.showelevatortable(data);
                    if(eyekey){
                        $('#thead_ck').click();
                    }
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    debugger;
                },
            });
        },
        clearform : function(){
            $("#elenum").html("0台");
            $("#eleamont").html("0元");
            $("#actForm #usingUnit").val("");
            $("#actForm #usingArea").val("");
            $("#actForm #usingAddress").val("");
            $("#actForm #acceptUnit").val("");
            $("#actForm select").val("");
            $("#actForm #startTime").val("");
            $("#actForm #endTime").val("");
            $('#InsureOrderListTable tbody').html("");
        },
        buildnull:function(value){
            if(value){
                return value;
            }else{
                return "";
            }
        },
        fixeddoubletwo:function(value){
            if(value){
                return parseFloat(value).toFixed(2);
            }else{
                return 0;
            }
        }
	};

}();

/*
 * Powered By [Code-Generator]
 * Web Site: http://www.hwelltech.com
 */

